<template>
  <view class="cu-form-group">
    <view class="title"><text v-if="required" class="text-red">*</text>{{title}}</view>
    <picker :disabled="disabled" mode="date"  @change="onPickerChange" :value="date">
      <view class="picker">
        {{date.length>0 ? date : placeholder}}
      </view>
    </picker>
  </view>
</template>

<script lang="ts" setup>
import {inject, ref, watchEffect} from "vue";
import moment from "moment";

interface CuDatePickerProps {
  required: boolean
  title: string
  disabled?: boolean
  placeholder?: string
  start?: string
  end?: string
  name?: string
}
const props = withDefaults(defineProps<CuDatePickerProps>(),{
  required: false,
  disabled: false,
  placeholder: '请选择'
})

const fields = inject<any>('fields')
const validate = inject<any>('validate')

const date = ref('')
watchEffect(() => {
	  if (props.name){
	    date.value = fields[props.name] || moment().format('YYYY-MM-DD')
	    if (props.required){
	      validate[props.name] = date.value.length > 0
	    }
	  }
  
})

const emit = defineEmits<{
  (e: 'change', value: any): void
}>()

function onPickerChange(e: any){
  const value = e.detail.value
  if (props.name){
    fields[props.name] = value
  }
  emit('change',value)
}
</script>

<style scoped lang="scss">

</style>
